<template>
  <div class="dib bsb w100 h100 vam count-down" @click="$emit('click', $event)">{{count | countFormat(format)}}</div>
</template>

<script>
  export default {
    name: "countdown",
    props: {
      max: {
        type: Number | String,
        default: 60
      },
      min: {
        type: Number | String,
        default: 0
      },
      text: {
        type: String,
        default: '获取验证码'
      },
      value: {
        type: Boolean,
        default: false,
      },
      format: {
        type: Function,
        default(val) {
          return val + 's后重新获取';
        },
      },
    },
    data() {
      return {
        count: this.text,
        lock: false,
        timer: null
      }
    },
    watch: {
      value(val) {
        val ? this.active() : this.stop();
      },
    },
    methods: {
      active() {
        let {lock, count, text} = this;
        if (lock || count !== text) return;
        this.lock = true;
        this.start(true);
      },
      start(init) {
        if (init) {
          this.count = this.max;
          this.$emit('starting', this);
        }
        this.timer = setTimeout(e => {
          this.count--;
          if (this.count > this.min) {
            this.start();
          } else {
            this.stop();
          }
        }, 1000);
      },
      stop() {
        clearTimeout(this.timer);
        this.timer = null;
        this.count = this.text;
        this.lock = false;
        this.$emit('ending', this);
      },
    },
    filters: {
      // 过滤倒计时显示的文本
      countFormat(count, format) {
        if (!isNaN(count)) {
          return format(count);
        } else {
          return count;
        }
      }
    }
  }
</script>
